﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DSAManager.Core;
using DSAManager.Models.Input;
using DSAManager.Models.Output;
using DSAManager.Utils;
using System.Net;
using EnterpriseDT.Net.Ftp;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace DSAManager
{
    public partial class FrmOrders : Form
    {
        public FrmOrders()
        {
            InitializeComponent();
        }

        //private ListView listOrders;
        private void FrmOrders_Load(object sender, EventArgs e)
        {
            initQueryCond();
            loadUnDownData(true);
        }

        void initQueryCond()
        {
            pageRequest = new PageRequest();
            txt_orderno.Clear();
            txt_wangwang.Clear();
            dpt_time1.Checked = false;
            dpt_time2.Checked = false;
            cbx_sortfield.SelectedIndex = 0;
            cbbSource.SelectedIndex = 0;
        }

        public void loadUnDownData(bool reload = false)
        {
            type = 0;
            refreshPageRequest(reload);

            var data = Api.QueryUnDownOrders(pageRequest);
            listOrders.Items.Clear();
            foreach (var info in data.data.Records)
            {
                var item = listOrders.Items.Add(new TreeListViewItem(info.no));
                item.SubItems.Add(info.wangwang);
                item.SubItems.Add(info.realnum.ToString());
                item.SubItems.Add(info.time.ToString("yyyy-MM-dd HH:mm:ss"));
                item.SubItems.Add(info.uploadnum.ToString());
                item.SubItems.Add(info.hasdownload ? "v" : "");
                item.SubItems.Add(info.downloadtime.HasValue ? info.downloadtime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "");
                item.SubItems.Add("");
                item.SubItems.Add(info.source == 0 ? "淘宝" : "微店");
                item.Tag = info;
            }

            handelPage(data.data);
        }

        private int endpage = 0;
        void handelPage(PageEntity<OrderInfo> pageEntity)
        {
            if (pageEntity.PageCount > 1)
            {
                pan_page.Show();
                lbl_pageinfo.Show();
                lbl_pageinfo.Text = string.Format("共{0}条记录,当前显示{1}-{2}条记录", pageEntity.RecordCount, pageEntity.Begin, pageEntity.End);
                lbl_page.Text = pageEntity.PageNo + "/" + pageEntity.PageCount;
                btn_index.Enabled = pageEntity.PageNo != 1;
                btn_previous.Enabled = pageEntity.PageNo != 1;
                btn_next.Enabled = pageEntity.PageNo < pageEntity.PageCount;
                btn_end.Enabled = pageEntity.PageNo != pageEntity.PageCount;
                endpage = (int)pageEntity.PageCount;
            }
            else
            {
                pan_page.Hide();
                lbl_pageinfo.Hide();
            }
        }

        void refreshPageRequest(bool reload)
        {
            pageRequest.pageSize = 20;
            if (reload)
            {
                pageRequest = new PageRequest();
                pageRequest.pageSize = 20;
                pageRequest.pageNo = 1;
                pageRequest.conds = "source:0";

            }


        }

        public void loadHasDownData(bool reload = false)
        {
            type = 1;
            refreshPageRequest(reload);

            chk_chkall.Checked = false;
            var data = Api.QueryHasDownOrders(pageRequest);
            listOrders.Items.Clear();
            foreach (var info in data.data.Records)
            {
                var item = listOrders.Items.Add(new TreeListViewItem(info.no));
                item.SubItems.Add(info.wangwang);
                item.SubItems.Add(info.realnum.ToString());
                item.SubItems.Add(info.time.ToString("yyyy-MM-dd HH:mm:ss"));
                item.SubItems.Add(info.uploadnum.ToString());
                item.SubItems.Add(info.hasdownload ? "v" : "");
                item.SubItems.Add(info.downloadtime.HasValue ? info.downloadtime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "");
                item.SubItems.Add(info.hassend ? "v" : "");
                item.SubItems.Add(info.source == 0 ? "淘宝" : "微店");
                item.Tag = info;
            }
            handelPage(data.data);
        }

        private void listOrders_SelectedIndexChanged(object sender, EventArgs e)
        {
            chk_chkall.Checked = false;
            var sel = listOrders.SelectedItems;
            if (sel.Count == 0) return;
            var orderInfo = sel[0].Tag as OrderInfo;
            lst_sizes.Items.Clear();
            foreach (var detail in orderInfo.details)
            {
                var item = lst_sizes.Items.Add(detail.size);
                item.SubItems.Add(detail.type);
                item.SubItems.Add(detail.parperAlias);
                item.SubItems.Add(detail.packagetype);
                item.SubItems.Add(detail.num.ToString());
                item.Tag = detail;
            }
        }

        private void chk_chkall_CheckedChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem order in listOrders.Items)
            {
                order.Checked = chk_chkall.Checked;
            }
        }

        List<string> downorders = new List<string>();
        string downpath = "";
        public void download()
        {
            try
            {
                var items = listOrders.CheckedItems;
                if (items.Count == 0)
                {
                    MsgBox.Alert("请选择需要下载的订单!");
                    return;
                }
                ///照片来源
                int source = 0;
                List<OrderInfo> orders = new List<OrderInfo>();
                foreach (ListViewItem item in items)
                {

                    OrderInfo info = item.Tag as OrderInfo;
                    orders.Add(info);
                    info.printwangwang = "";
                }

                for (int i = 0; i < orders.Count; i++)
                {
                    source = orders[0].source;
                    orders[i].printwangwang = (i + 1).ToString().PadLeft(2, '0') + "_" + orders[i].wangwang;
                }

                //要保证同一个旺旺号的，编号一致


                string path = Application.StartupPath + "\\下载记录\\" + DateTime.Now.ToString("yyyyMMddHHmmss");
                if (!string.IsNullOrEmpty(AppContext.down_dir))
                    path = Path.Combine(AppContext.down_dir, DateTime.Now.ToString("yyyyMMddHHmmss"));

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                #region 淘宝订单下载
                if (source == 0)
                {
                    BackgroundWorker bk = new BackgroundWorker();
                    bk.WorkerReportsProgress = true;
                    bk.DoWork += delegate
                                     {
                                         //先分析出下载文件名,保存路径,对应的url,复制份数
                                         downorders = new List<string>();
                                         int file_seq = 0;
                                         List<downEntity> downEntities = new List<downEntity>();
                                         if (AppContext.save_mode == 0)
                                         {
                                             foreach (var info in orders)
                                             {
                                                 downorders.Add(info.no);
                                                 foreach (var detail in info.details)
                                                 {
                                                     string plusPath = detail.paper + "\\" + detail.printSize + "\\" + info.printwangwang;
                                                     string savepath = Path.Combine(path, plusPath);
                                                     if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath);
                                                     detail.savepath = savepath;
                                                     //保存
                                                     string logpath = Application.StartupPath + "\\downlog";
                                                     if (!Directory.Exists(logpath)) Directory.CreateDirectory(logpath);
                                                     File.WriteAllText(logpath + "\\" + detail.no + ".txt", detail.savepath);
                                                     foreach (var image in detail.images)
                                                     {
                                                         string fileName = detail.size + "_" + (++file_seq) + ".jpg";
                                                         if (detail.type == "拍立得")
                                                         {
                                                             fileName = "[拍立得]" + fileName;
                                                         }
                                                         downEntity entity = new downEntity();
                                                         entity.fileName = savepath + "\\" + fileName;
                                                         entity.path = savepath;
                                                         entity.url = image.url;
                                                         entity.num = image.num;

                                                         downEntities.Add(entity);
                                                     }
                                                 }
                                             }
                                         }

                                         if (AppContext.save_mode == 1)
                                         {
                                             downorders = new List<string>();
                                             foreach (var info in orders)
                                             {
                                                 //针对合并后成为一个尺寸的，进行合并到一个尺寸
                                                 //info.ReBuilderDetail();

                                                 downorders.Add(info.no);

                                                 //1、下载客人相片后的文件夹只有一个（F为富士相纸，K为柯达相纸）比如客人拍  3F光、3F绒、4K光、5K光、8F光、8F绒、10F光，那么下载后得到的文件夹就只有一个：以“3F光、3F绒、4K光、5K光、8F光、8F绒、10F光+淘宝名+收件人姓名+订单号 ”命名的文件夹，下级文件夹便是 3F光、3F绒、4K光、5K光、8F光、8F绒、10F光单独命名的文件夹，如果一个尺寸比如3F光里面相片客户需要洗多种份数，那么在3F下另起多个子文件夹分别用1份、2份、3份、、、命名，如果只有一份遍不另起一级。如图：

                                                 //1个订单的所有图片都放到同一个文件夹中
                                                 string plusPath = info.getSavePath();
                                                 string savepath = Path.Combine(path, plusPath);
                                                 if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath);

                                                 foreach (var detail in info.details)
                                                 {

                                                     detail.savepath = savepath + "\\" + detail.pathName;
                                                     if (!Directory.Exists(detail.savepath))
                                                         Directory.CreateDirectory(detail.savepath);
                                                     //保存
                                                     string logpath = Application.StartupPath + "\\downlog";
                                                     if (!Directory.Exists(logpath)) Directory.CreateDirectory(logpath);
                                                     File.WriteAllText(logpath + "\\" + detail.no + ".txt", detail.savepath);

                                                     //如果图片都是1份的就直接保存，否则需要按份数分开保存
                                                     if (detail.checkAllIsSigle())
                                                     {
                                                         foreach (var image in detail.images)
                                                         {
                                                             string fileName = detail.size + "_" + (++file_seq) + ".jpg";
                                                             if (detail.type == "拍立得")
                                                             {
                                                                 fileName = "[拍立得]" + fileName;
                                                             }
                                                             downEntity entity = new downEntity();
                                                             entity.fileName = detail.savepath + "\\" + fileName;
                                                             entity.path = savepath;
                                                             entity.url = image.url;
                                                             entity.num = image.num;

                                                             downEntities.Add(entity);
                                                         }
                                                     }
                                                     else
                                                     {
                                                         foreach (var image in detail.images)
                                                         {
                                                             image.savepath = detail.savepath + "\\" + image.num + "份";
                                                             if (!Directory.Exists(image.savepath))
                                                                 Directory.CreateDirectory(image.savepath);

                                                             string fileName = detail.size + "_" + (++file_seq) + ".jpg";
                                                             if (detail.type == "拍立得")
                                                             {
                                                                 fileName = "[拍立得]" + fileName;
                                                             }
                                                             downEntity entity = new downEntity();
                                                             entity.fileName = image.savepath + "\\" + fileName;
                                                             entity.path = savepath;
                                                             entity.url = image.url;
                                                             entity.num = 1;// image.num;

                                                             downEntities.Add(entity);
                                                         }


                                                     }

                                                 }
                                             }
                                         }



                                         //开始下载
                                         for (int i = 0; i < downEntities.Count; i++)
                                         {
                                             var downinfo = downEntities[i];
                                             int per = (int)(((decimal)i / (decimal)downEntities.Count) * 100);
                                             bk.ReportProgress(per);
                                             downImage(downinfo);
                                             if (downinfo.num > 1 && File.Exists(downinfo.fileName))
                                             {
                                                 for (int j = 0; j < downinfo.num - 1; j++)
                                                 {
                                                     string newFile = downinfo.fileName.Replace(".jpg",
                                                                                                "_" + (j + 1) + ".jpg");
                                                     File.Copy(downinfo.fileName, newFile);
                                                 }
                                             }
                                         }

                                         //更新至服务器
                                         List<string> ids = new List<string>();
                                         foreach (var info in orders)
                                         {
                                             ids.Add(info.no);
                                         }
                                         var ret = Api.SetOrderHasDown(ids);
                                         Console.WriteLine(ret);
                                         downpath = path;
                                     };
                    bk.RunWorkerCompleted += delegate
                                                 {
                                                     AppContext.ProgressBar.Visible = false;
                                                     AppContext.downbutton.Enabled = true;
                                                     MsgBox.Alert("下载完成!");
                                                     Process.Start(path);
                                                 };
                    bk.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                                              {
                                                  AppContext.ProgressBar.Value = e.ProgressPercentage;
                                              };
                    bk.RunWorkerAsync();
                }
                #endregion
                #region 微店订单下载逻辑
                else
                {
                    BackgroundWorker bkWeidian = new BackgroundWorker();
                    bkWeidian.WorkerReportsProgress = true;
                    bkWeidian.DoWork += delegate
                    {
                        downorders = new List<string>();
                        var configList = ReadConfig();
                        var photoSizeList = Api.QueryPhotosize().data;
                        int file_seq = 0;
                        foreach (var info in orders)
                        {
                            string plusPath = info.getSavePath();
                            string savepath = Path.Combine(path, plusPath);
                            if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath);

                            foreach (var detail in info.details)
                            {
                                detail.savepath = savepath + "\\" + detail.pathName;
                                if (!Directory.Exists(detail.savepath))
                                    Directory.CreateDirectory(detail.savepath);
                                //保存
                                string logpath = Application.StartupPath + "\\downlog";
                                if (!Directory.Exists(logpath)) Directory.CreateDirectory(logpath);
                                File.WriteAllText(logpath + "\\" + detail.no + ".txt", detail.savepath);
                                //获取拍立得照片配置
                                var config = configList.Find((PailideConfig p) => p.Size == detail.size && p.PictureType == detail.type);
                                //获取普通照片尺寸
                                var photoSize = photoSizeList.Find((PhotoSizeInfo p) => p.name == detail.size);

                                //如果需要合并普通照片和拍立得照片3、4寸 则新建立文件夹
                                if (detail.size == "3寸" || detail.size == "4寸")
                                {
                                    detail.savepath = savepath + "\\" + detail.pathName + "\\template";
                                    if (!Directory.Exists(detail.savepath))
                                        Directory.CreateDirectory(detail.savepath);
                                }
                                //判断订单图片渠道
                                foreach (var image in detail.images)
                                {
                                    string fileName = detail.size + "_" + (++file_seq) + ".jpg";
                                    if (detail.type == "拍立得")
                                    {
                                        fileName = "[拍立得]" + fileName;
                                    }
                                    if (detail.uploadtype == 1)//不裁减通道,原图下载
                                    {
                                        ParseOriginalImg(detail.savepath, fileName, image.url, image.num);
                                    }
                                    else
                                    {
                                        if (image.sellerCut)//卖家裁剪，直接原图下载
                                        {
                                            ParseOriginalImg(detail.savepath, fileName, image.url, image.num);
                                        }
                                        else if (image.IsCut)//自主裁剪
                                        {
                                            var imgUrl = ParseImgUrl(image);
                                            switch (detail.type)
                                            {
                                                case "普通照片":
                                                case "正方形":
                                                    ParseCutImg(detail.savepath, fileName, imgUrl, image.num);//只裁剪
                                                    break;
                                                case "拍立得":
                                                    ParsePailideCutImg(detail.savepath, fileName, imgUrl, image.num, config);
                                                    break;
                                            }
                                        }
                                        else//留白
                                        {
                                            var imgUrl = ParseImgUrl(image);
                                            //获取照片冲洗实际大小
                                            ParseLiubaiCutImg(detail.savepath, fileName, imgUrl, image.num, photoSize);
                                        }
                                    }

                                }

                                #region 合并照片逻辑
                                //判断是否需要合并照片
                                if (detail.size == "3寸" || detail.size == "4寸")
                                {
                                    //开始合并照片
                                    DirectoryInfo TheFolder = new DirectoryInfo(detail.savepath);
                                    var allFile = TheFolder.GetFiles();

                                    detail.savepath = savepath + "\\" + detail.pathName;//重新定位照片文件夹位置

                                    //遍历文件
                                    for (var i = 0; i < allFile.Length; i++)// (FileInfo NextFile in TheFolder.GetFiles())
                                    {
                                        string fileName = detail.size + "_" + (++file_seq) + ".jpg";
                                        if (detail.type == "拍立得")
                                        {
                                            fileName = "[拍立得]" + fileName;
                                        }

                                        Image img1 = Image.FromFile(allFile[i].FullName);//获取第一张图片
                                        Image img2 = null;
                                        if (i + 1 < allFile.Length)
                                            img2 = Image.FromFile(allFile[i + 1].FullName);//获取第二张图片
                                        if (img2 == null)
                                        {
                                            img2 = (Image)img1.Clone();
                                            //创建空白图片
                                            Graphics g = Graphics.FromImage(img2);
                                            //清除画布,背景设置为白色
                                            g.Clear(System.Drawing.Color.White);
                                            g.Dispose();

                                        }
                                        //检测大小，缩放图片
                                        if (img1.Width > img2.Width)
                                        {
                                            Bitmap backgroudImg = null;
                                            //创建要显示的图片对象,根据参数的个数设置宽度
                                            backgroudImg = new Bitmap(img2.Width * 2, img2.Height, PixelFormat.Format24bppRgb);

                                            Graphics g = Graphics.FromImage(backgroudImg);
                                            //清除画布,背景设置为白色
                                            g.Clear(System.Drawing.Color.White);
                                            g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
                                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                            g.CompositingQuality = CompositingQuality.HighQuality;
                                            //填充第一张图片
                                            g.DrawImage(img1, 0, 0, img2.Width, img2.Height);

                                            //填充第二张图片
                                            g.DrawImage(img2, img2.Width, 0, img2.Width, img2.Height);

                                            backgroudImg.Save(detail.savepath + "\\" + fileName, ImageFormat.Jpeg);
                                            g.Dispose();
                                            backgroudImg.Dispose();
                                            img1.Dispose();
                                            img2.Dispose();
                                        }
                                        else
                                        {
                                            Bitmap backgroudImg = null;
                                            //创建要显示的图片对象,根据参数的个数设置宽度
                                            backgroudImg = new Bitmap(img1.Width * 2, img1.Height, PixelFormat.Format24bppRgb);

                                            Graphics g = Graphics.FromImage(backgroudImg);
                                            //清除画布,背景设置为白色
                                            g.Clear(System.Drawing.Color.White);
                                            g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
                                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                            g.CompositingQuality = CompositingQuality.HighQuality;
                                            //填充第一张图片
                                            g.DrawImage(img1, 0, 0, img1.Width, img1.Height);

                                            //填充第二张图片
                                            g.DrawImage(img2, img1.Width, 0, img1.Width, img1.Height);

                                            backgroudImg.Save(detail.savepath + "\\" + fileName, ImageFormat.Jpeg);
                                            g.Dispose();
                                            backgroudImg.Dispose();
                                            img1.Dispose();
                                            img2.Dispose();
                                        }
                                        i++;
                                    }
                                    //清空文件夹
                                    TheFolder.Delete(true);
                                }
                                #endregion

                            }
                        }
                    };
                    bkWeidian.RunWorkerCompleted += delegate
                    {
                        AppContext.ProgressBar.Visible = false;
                        AppContext.downbutton.Enabled = true;
                        MsgBox.Alert("下载完成!");
                        Process.Start(path);
                    };
                    bkWeidian.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                    {
                        AppContext.ProgressBar.Value = e.ProgressPercentage;
                    };
                    bkWeidian.RunWorkerAsync();
                }
                #endregion
                AppContext.ProgressBar.Visible = true;
                AppContext.downbutton.Enabled = false;
            }
            catch (Exception ex)
            {
                MsgBox.Alert(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        /// <summary>
        /// 原图解析
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="fileName"></param>
        /// <param name="imgUrl"></param>
        /// <param name="num"></param>
        void ParseOriginalImg(string savePath, string fileName, string imgUrl, int num)
        {
            var downfilename = savePath + "\\" + fileName;
            downImage(new downEntity()
            {
                url = imgUrl,
                fileName = downfilename
            });

            if (num > 1 && File.Exists(downfilename))
            {
                for (int j = 0; j < num - 1; j++)
                {
                    string newFile = downfilename.Replace(".jpg", "_" + (j + 1) + ".jpg");
                    File.Copy(downfilename, newFile);//复制图片
                }
            }
        }

        /// <summary>
        /// 裁剪照片
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="fileName"></param>
        /// <param name="imgUrl"></param>
        /// <param name="num"></param>
        void ParseCutImg(string savePath, string fileName, string imgUrl, int num)
        {
            var downfilename = savePath + "\\" + fileName;
            downImage(new downEntity()
            {
                url = imgUrl,
                fileName = downfilename
            });

            if (num > 1 && File.Exists(downfilename))
            {
                for (int j = 0; j < num - 1; j++)
                {
                    string newFile = downfilename.Replace(".jpg", "_" + (j + 1) + ".jpg");
                    File.Copy(downfilename, newFile);//复制图片
                }
            }
        }

        /// <summary>
        /// 解析拍立得照片
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="fileName"></param>
        /// <param name="imgUrl"></param>
        /// <param name="num"></param>
        /// <param name="config"></param>
        void ParsePailideCutImg(string savePath, string fileName, string imgUrl, int num, PailideConfig config)
        {
            var downfilename = savePath + "\\" + fileName;
            Image img = downImage(imgUrl);
            //生成拍立得照片
            int leftbk = (int)((config.LeftFrame) * img.Width / config.ImgHeight);
            int rightbk = (int)((config.RightFrame) * img.Width / config.ImgHeight);
            int upbk = (int)((config.UpFrame) * img.Height / config.ImgWidth);
            int downbk = (int)((config.DownFrame) * img.Height / config.ImgWidth);

            Bitmap backgroudImg = null;
            //创建要显示的图片对象,根据参数的个数设置宽度
            //backgroudImg = new Bitmap(leftbk + img.Width + rightbk, upbk + downbk + img.Height, PixelFormat.Format24bppRgb);
            backgroudImg = new Bitmap(downbk + img.Width + upbk, leftbk + rightbk + img.Height, PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage(backgroudImg);
            //清除画布,背景设置为白色
            g.Clear(System.Drawing.Color.White);
            g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.CompositingQuality = CompositingQuality.HighQuality;
            //g.DrawImage(img, leftbk, upbk, img.Width, img.Height);
            g.DrawImage(img, downbk, leftbk, img.Width, img.Height);

            backgroudImg.Save(downfilename, ImageFormat.Jpeg);
            g.Dispose();
            backgroudImg.Dispose();
            img.Dispose();

            if (num > 1 && File.Exists(downfilename))
            {
                for (int j = 0; j < num - 1; j++)
                {
                    string newFile = downfilename.Replace(".jpg", "_" + (j + 1) + ".jpg");
                    File.Copy(downfilename, newFile);//复制图片
                }
            }
        }

        void ParseLiubaiCutImg(string savePath, string fileName, string imgUrl, int num, PhotoSizeInfo config)
        {
            var downfilename = savePath + "\\" + fileName;
            Image img = downImage(imgUrl);
            float radioConfig = config.width / config.height;
            float radioImg = img.Width / img.Height;

            if (radioConfig > radioImg)//高度为准,宽留白
            {
                //计算图片实际冲洗大小
                int iw = Convert.ToInt32(config.width * img.Height / config.height);
                int ih = img.Height;
                Bitmap backgroudImg = null;
                //创建要显示的图片对象,根据参数的个数设置宽度
                //backgroudImg = new Bitmap(leftbk + img.Width + rightbk, upbk + downbk + img.Height, PixelFormat.Format24bppRgb);
                backgroudImg = new Bitmap(iw, ih, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(backgroudImg);
                //清除画布,背景设置为白色
                g.Clear(System.Drawing.Color.White);
                g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.HighQuality;
                //g.DrawImage(img, leftbk, upbk, img.Width, img.Height);
                g.DrawImage(img, (backgroudImg.Width - img.Width) / 2, 0, img.Width, img.Height);

                backgroudImg.Save(downfilename, ImageFormat.Jpeg);
                g.Dispose();
                backgroudImg.Dispose();
                img.Dispose();
            }
            else//宽度为准,高留白
            {
                //计算图片实际冲洗大小
                int iw = img.Width;
                int ih = Convert.ToInt32(config.height * img.Width / config.width);
                Bitmap backgroudImg = null;
                //创建要显示的图片对象,根据参数的个数设置宽度
                //backgroudImg = new Bitmap(leftbk + img.Width + rightbk, upbk + downbk + img.Height, PixelFormat.Format24bppRgb);
                backgroudImg = new Bitmap(iw, ih, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(backgroudImg);
                //清除画布,背景设置为白色
                g.Clear(System.Drawing.Color.White);
                g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.HighQuality;
                //g.DrawImage(img, leftbk, upbk, img.Width, img.Height);
                g.DrawImage(img, 0, (backgroudImg.Height - img.Height) / 2, img.Width, img.Height);

                backgroudImg.Save(downfilename, ImageFormat.Jpeg);
                g.Dispose();
                backgroudImg.Dispose();
                img.Dispose();
            }
        }

        /// <summary>
        /// 解析图片地址
        /// </summary>
        /// <param name="imgInfo"></param>
        /// <returns></returns>
        string ParseImgUrl(OrderImage imgInfo)
        {
            string imgurl = imgInfo.url;
            if (imgInfo.IsCut)
            {
                var radio = imgInfo.Width / imgInfo.WidgetWidth;
                //获取裁剪框大小
                decimal CutWidth = (imgInfo.EndX - imgInfo.BeginX) * radio;
                decimal CutHeight = (imgInfo.EndY - imgInfo.BeginY) * radio;

                //计算偏移
                decimal OffsetX = imgInfo.BeginX * radio;
                decimal OffsetY = imgInfo.BeginY * radio;
                imgurl = imgurl + "?imageMogr2/rotate/" + imgInfo.rotateangle + "/crop/!" + CutWidth + "x" + CutHeight + "a" + OffsetX + "a" + OffsetY;
            }
            return imgurl;
        }

        /// <summary>
        /// 读取拍立得配置文件
        /// </summary>
        /// <returns></returns>
        private List<PailideConfig> ReadConfig()
        {
            List<PailideConfig> result = new List<PailideConfig>();
            try
            {
                StreamReader rsf = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\config\\pailide.dat");
                string strConfig = "";
                while (rsf.Peek() >= 0)
                {
                    strConfig += rsf.ReadLine();
                }
                rsf.Close();
                result = JsonHelper.DeserializeObject<List<PailideConfig>>(strConfig);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
            return result;
        }

        void downImage(downEntity downinfo)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFile(downinfo.url, downinfo.fileName);
        }

        Image downImage(string imgUrl)
        {
            WebClient webClient = new WebClient();
            var imgByte = webClient.DownloadData(imgUrl);
            MemoryStream ms = new MemoryStream(imgByte);
            Image image = System.Drawing.Image.FromStream(ms);
            return image;
        }

        public void sendimages()
        {
            try
            {

                if (!Directory.Exists(AppContext.share_dir))
                {
                    MsgBox.Alert("服务器共享目录不存在,请正确设置!");
                    return;
                }

                if (!Directory.Exists(downpath) || downorders.Count == 0)
                {
                    MsgBox.Alert("请先下载照片!");
                    return;
                }

                var path = Application.StartupPath + "\\下载记录";
                if (!string.IsNullOrEmpty(AppContext.down_dir))
                    path = AppContext.down_dir;

                //List<string> subDirs = new List<string>(Directory.GetDirectories(path));
                //if (subDirs.Count == 0)
                //{
                //    MsgBox.Alert("请先下载照片!");
                //    return;
                //}
                //subDirs.Sort();
                var imagepath = downpath;// subDirs[subDirs.Count - 1];
                BackgroundWorker bk = new BackgroundWorker();
                bk.WorkerReportsProgress = true;
                bk.DoWork += delegate
                                 {
                                     try
                                     {


                                         //先删除之前的照片
                                         string img_path = Path.Combine(AppContext.share_dir, "照片");
                                         if (Directory.Exists(img_path))
                                             Directory.Delete(img_path, true);
                                         Directory.CreateDirectory(img_path);

                                         var files = Directory.GetFiles(imagepath, "*.jpg", SearchOption.AllDirectories);
                                         for (int i = 0; i < files.Length; i++)
                                         {
                                             int per = (int)(((decimal)i / (decimal)files.Length) * 100);
                                             bk.ReportProgress(per);
                                             string file = files[i];
                                             string r_path = Path.Combine(AppContext.share_dir,
                                                                          "照片" +
                                                                          Path.GetDirectoryName(file).Replace(
                                                                              imagepath, ""));
                                             if (!Directory.Exists(r_path))
                                                 Directory.CreateDirectory(r_path);
                                             string r_filename = Path.Combine(r_path, Path.GetFileName(file));
                                             File.Copy(file, r_filename);
                                         }

                                         //更新至服务器
                                         List<string> ids = new List<string>();
                                         foreach (var info in downorders)
                                         {
                                             ids.Add(info);
                                         }
                                         var ret = Api.SetOrderHasSend(ids);
                                         Console.WriteLine(ret);

                                     }
                                     catch (Exception ex)
                                     {

                                         MsgBox.Alert(ex.Message + Environment.NewLine + ex.StackTrace);
                                     }
                                 };
                bk.RunWorkerCompleted += delegate
                                             {
                                                 AppContext.ProgressBar.Visible = false;
                                                 AppContext.downbutton.Enabled = true;
                                                 MsgBox.Alert("上传照片至打印服务器完成!");
                                             };
                bk.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                {
                    AppContext.ProgressBar.Value = e.ProgressPercentage;
                };
                bk.RunWorkerAsync();
                AppContext.ProgressBar.Visible = true;
                AppContext.downbutton.Enabled = false;

            }
            catch (Exception ex)
            {
                MsgBox.Alert(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        class downEntity
        {
            public string path { get; set; }
            public string fileName { get; set; }
            public string url { get; set; }
            public int num { get; set; }
        }

        void down_inner()
        {

        }

        private void lst_sizes_DoubleClick(object sender, EventArgs e)
        {
            var sel = lst_sizes.SelectedItems;
            if (sel.Count == 0) return;
            var item = lst_sizes.SelectedItems[0].Tag as OrderDetail;
            string logpath = Application.StartupPath + "\\downlog\\" + item.no + ".txt";
            if (File.Exists(logpath))
            {
                string path = File.ReadAllText(logpath);
                if (Directory.Exists(path))
                    Process.Start(path);
            }
        }


        private PageRequest pageRequest;



        private void btn_index_Click(object sender, EventArgs e)
        {
            pageRequest.pageNo = 1;
            queryData();
        }

        private void btn_previous_Click(object sender, EventArgs e)
        {
            pageRequest.pageNo -= 1;
            queryData();
        }

        private void btn_next_Click(object sender, EventArgs e)
        {
            pageRequest.pageNo += 1;
            queryData();
        }

        private void btn_end_Click(object sender, EventArgs e)
        {
            pageRequest.pageNo = endpage;
            queryData();
        }

        private int type = 0;

        void queryData()
        {
            if (type == 0)
                loadUnDownData();
            else
            {
                loadHasDownData();
            }
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            pageRequest = new PageRequest();
            pageRequest.pageNo = 1;

            if (cbx_sortfield.SelectedIndex == 0)
                pageRequest.order = "created desc";
            else
            {
                pageRequest.order = "downloadtime desc";
            }

            string cond = "";
            if (cbbSource.SelectedIndex == 0)
            {
                if (!string.IsNullOrEmpty(cond))
                    cond += "|";
                cond += "source:0";
            }
            else
            {
                if (!string.IsNullOrEmpty(cond)) cond += "|";
                cond += "source:1";
            }
            if (!string.IsNullOrEmpty(txt_orderno.Text.Trim()))
            {
                if (!string.IsNullOrEmpty(cond)) cond += "|";
                cond += "orderno:" + txt_orderno.Text.Trim();
            }

            if (!string.IsNullOrEmpty(txt_wangwang.Text.Trim()))
            {
                if (!string.IsNullOrEmpty(cond)) cond += "|";
                cond += "wangwang:" + txt_wangwang.Text.Trim();
            }

            if (dpt_time1.Checked)
            {
                if (!string.IsNullOrEmpty(cond)) cond += "|";
                cond += "time1:" + new DateTime(dpt_time1.Value.Date.Ticks).ToString("yyyyMMddHHmmss");
            }

            if (dpt_time2.Checked)
            {
                if (!string.IsNullOrEmpty(cond)) cond += "|";
                cond += "time2:" + new DateTime(dpt_time2.Value.Date.AddDays(1).AddMilliseconds(-1).Ticks).ToString("yyyyMMddHHmmss");
            }
            pageRequest.conds = cond;
            queryData();
        }

    }
}
